<template>
	<div class="wy-back-f7">
		<div class="container-940">
			<a-row class="home-page-title">
				<nuxt-link to="/">返回首页</nuxt-link>
		    </a-row>
			<div class="register-tab">
				<h2>注册账号</h2>
				<p>REGISTER AN ACCOUNT</p>
				<a-tabs @change="loginType" type="card" class='register-main'>
					<a-tab-pane tab="企业用户" key="2"></a-tab-pane>
					<a-tab-pane tab="个人用户" key="1"></a-tab-pane>
				</a-tabs>
				<a-form :form="form" @submit="handleSubmit">
					<a-form-item v-bind="formItemLayout" label="企业类型" v-if="type == 2">
						<a-select v-decorator="['companyType', {rules: [{ required: true, message: '请选择企业类型' }]} ]" placeholder="请选择">
							<a-select-option value="1">境内企业</a-select-option>
							<a-select-option value="2">境外企业</a-select-option>
						</a-select>
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="企业名称" v-if="type == 2">
						<a-input v-decorator="['company', { rules: [ {required: true,pattern: regAll.regCompanyName, message: '企业名称应符合规则，不少于4个汉字'}]}]" maxLength="50" />
					</a-form-item>


					<a-form-item v-bind="formItemLayout" label="登录名" extra="长度为6-16个字符，支持字母数字和@符号组成，不能使用空格。">
						<a-input v-decorator="[ 'username', { rules: [ {required: true, message: '登录名格式不正确!', pattern: regAll.regUserName,}]}]" maxLength="20" />
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="密码" >
						<a-input v-decorator="['password', { rules: [{required: true,pattern: regAll.regPassword, message: '密码格式不正确!',}],} ]" type="password" placeholder="6-20位英文或字母" @keyup="checkStrength" maxLength='32' />
						<div class="pass-auth">
							<span :class="passGrade!=''?'red':''"></span>
							<span :class="passGrade =='yellow'||passGrade =='green'?'yellow':''"></span>
							<span :class="passGrade=='green'?'green':''"></span>
							<a :class="''+passGrade">{{passGrade==='red'?'低':(passGrade==='yellow'?'中':(passGrade==='green'?'高':''))}}</a>
						</div>
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="确认密码">
						<a-input v-decorator="['password2',{rules: [{required: true, message: '您输入的两个密码不一致',}, {validator: compareToFirstPassword,}],}]" type="password" @blur="handleConfirmBlur" maxLength='32' />
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="真实姓名">
						<a-input v-decorator="['nickName',{rules: [{required: true,pattern: regAll.regName, message: '真实姓名格式不正确!'}] } ]"  maxLength="48" />
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="电子邮箱">
						<!-- <a-input v-decorator="[ 'email', { rules: [{required: false, type: 'email', message: '输入的电子邮件无效!', }]} ]"  maxLength="64"/> -->
						<a-input v-decorator="['email', { rules: [ {required: true,pattern: regAll.regEmail, message: '输入的电子邮件无效!'}]}]" maxLength="64" />
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="性别"  v-if="type == 1">
						<a-select v-decorator="[ 'ssex', {rules: [{message: '请选择性别!' }]} ]" placeholder="请选择">
							<a-select-option value="0">男</a-select-option>
							<a-select-option value="1">女</a-select-option>
						</a-select>
					</a-form-item>
					

					<a-form-item v-bind="formItemLayout" label="联系地址" v-if="type == 1">
						<a-input v-decorator="['address']" />
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="手机号码">
						<a-input v-decorator="[
				          'mobile',{
				            rules: [{ required: true, validator: checkTel}],
				          }
				        ]"  maxLength="13">
						</a-input>
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="验证码">
						<a-row :gutter="8">
							<a-col :span="15">
								<a-input v-decorator="['imgCode',{rules: [{ required: true, message: '请输入验证码!' }]}]"  maxLength="6" style="width: 247px" />
							</a-col>
							<a-col :span="9">
								<img class="img-code" @click="getCodeUrl" :src="codeUrl" />
							</a-col>
						</a-row>
					</a-form-item>
					<a-form-item v-bind="formItemLayout" label="短信验证码:">
						<a-row :gutter="8">
							<a-col :span="15">
								<a-input v-decorator="[
				          'smsCode',
				          {rules: [{ required: true, message: '请输入你的验证码!' }]}
				        ]"  maxLength="6" style="width: 247px" />
							</a-col>
							<a-col :span="9">
								<a-button class="ant-btn-code" @click="SmsMsgSend">{{smsCodeText}}{{smsCodeText=='获取验证码'?'':'S'}}</a-button>
							</a-col>
						</a-row>
					</a-form-item>
					<a-divider />
					<a-form-item  style="margin: 0 72px;">
						<a-checkbox v-decorator="['agreement', {valuePropName: 'checked',rules: [{validator: validateAgreement}]}]">
							本人保证: 以上填写内容和材料附件真实无误，若填写或提供任何错误、不实或不完整的资料导致发生任何经济及法律纠纷，本人愿承担一切责任！
						</a-checkbox>
					</a-form-item>
					<a-form-item style="text-align: center;margin-bottom: 80px;">
						<a-button type="primary" html-type="submit" class="ant-btn-register" block>立即注册</a-button>
					</a-form-item>
				</a-form>
			</div>
		</div>
	</div>
</template>
<script>
	import { environment } from '@/server/environment'
	import { regAll } from'@/utils/formValidate'
	export default {
		data() {
			return {
				regAll: regAll,
				confirmDirty: false,
				formItemLayout: {
					labelCol: {
						xs: {
							span: 24
						},
						sm: {
							span: 8
						},
					},
					wrapperCol: {
						xs: {
							span: 24
						},
						sm: {
							span: 10
						},
					}
				},
				
				roleList: [],
				// 当前密码等级
				passGrade: '',
				// 验证码
				codeUrl: '',
				// option:{
					username: '', // 用户名
					password: '', // 用户密码
					password2: '', // 确认密码
					nickName: '', // 真实姓名
					ssex: '', // 性别:0=男,1=女,2=保密
					email: '', // 邮箱
					detailAddress: '', // 详细地址
					mobile: '', // 手机号

					deptId: '', // 部门ID
					deptName: '', // 部门
					
					
					status: 1, // 状态:0=锁定,1=有效
					
					description: '', // 个人描述
					avatar: '', // 用户头像
					roleId: '1', // 角色id
					roleName: '', // 角色
					
					certificatesType: '', // 证件类型
					certificatesNo: '', // 证据号码
					certificatesjpg: '', // 证件扫描件/营业执照扫描件
					companyType: '', // 企业类型
					company: '', // 企业名字
					companyCreateTime: '', // 企业创建时间
					legalPerson: '', // 法人/企业负责人
					
					type: 2, // 1个人/2企业
					certificatesPath: '', // 证件存放目录
					// roleType: '1', // 初始化角色：1普通用户角色 2：简单注册角色
				// }
				smsCodeText: '获取验证码',
				// 验证码倒计时
				smsInterval: null,
				SmsMsgSendFlag: false
			}
		},
		beforeCreate() {
			this.form = this.$form.createForm(this);
		},
		created() {
			this.getCodeUrl();
		},
		components: {
			// Footer
		},
		watch: {},

		mounted: function() {

		},
		methods: {
			// 登录名
			checkUserName (rule, value, callback) {
				const form = this.form;
				if (!regAll.regUserName.test(form.getFieldValue('username'))) {
					callback('登录名格式不正确!');
				} else {
					callback();
				}
			},
			// 校验手机号
			checkTel (rule, value, callback) {
				const form = this.form;
				if (form.getFieldValue('mobile')!=''&&!regAll.regTel.test(form.getFieldValue('mobile'))) {
					callback('请输入合法的手机号码!');
				} else {
					callback();
				}
			},
			// 校验公司
			checkCompanyName (rule, value, callback) {
				const form = this.form;
				let str = form.getFieldValue('company').replace(/[^\x00-\xff]/g,"aa");
				// console.log('dddd;',form.getFieldValue('company'))
				if (form.getFieldValue('company')!=''&&!regAll.regCompanyName.test(form.getFieldValue('company'))) {
			        callback('企业名称应符合规则，不少于4个汉字或8个字符!');
				} else {
					callback();
				}
			},
			//检测密码		
			validateToNextPassword(rule, value, callback) {
				const form = this.form;
				if (form.getFieldValue('password')!=''&&!regAll.regPassword.test(form.getFieldValue('password'))) {
					callback('密码格式不正确!');
				} else {
					callback();
				}
			},
			// 真实姓名
			checkName(rule, value, callback) {
				const form = this.form;
				let str = form.getFieldValue('company').replace(/[^\x00-\xff]/g,"aa");
				if (!regAll.regName.test(str)) {
			        callback('真实姓名格式不正确!');
				} else {
					callback();
				}
			},
			// 获取验证码
			getCodeUrl () {
				this.codeUrl = environment.APIUrl+'/gifCode?v=' + new Date().getTime() 
				this.SmsMsgSendFlag = false
			},
			//tab切换事件
			loginType(key) {
				this.getCodeUrl();
				// this.form.resetFields();
				// console.log('aaa:',key)
				this.type = parseInt(key);
				this.form = this.$form.createForm(this);
				this.passGrade = '';
			},
			// 个人注册提交
			handleSubmit(e) {
				e.preventDefault();
				// this.form.resetFields();
				this.form.validateFieldsAndScroll((err, values) => {
					// console.log('err, values::',err, values)
					if(!err) {
						// console.log('Received values of form: ', values);
						values.type = this.type;
						values.roleId = this.roleId;		
						this.userRegists(values);
						// this.$router.push('/Login');
					}
				});
			},
			//检测确认密码
			handleConfirmBlur(e) {
				const value = e.target.value;
				this.confirmDirty = this.confirmDirty || !!value;
			},
			//检测确认密码
			compareToFirstPassword(rule, value, callback) {
				const form = this.form;
				if(value && value !== form.getFieldValue('password')) {
					callback('您输入的两个密码不一致!');
				} else {
					callback();
				}
			},
			// 密码高中低验证
			checkStrength (){ 
				var lv = 0; 
				var val = this.form.getFieldValue('password');
				if (val){
					if(val.match(/[a-z]/g)){lv++;} 
					if(val.match(/[0-9]/g)){lv++;} 
					if(val.match(/(.[^a-z0-9])/g)){lv++;} 
					if(val.length < 6){lv=0;} 
					if(lv > 3){
						lv=3;
					} 
					this.passGrade = (lv === 1?'red':(lv === 2? 'yellow': (lv === 3?'green':'')))
				}
				if (this.form.getFieldValue('password2')&&this.form.getFieldValue('password')!=this.form.getFieldValue('password2')){
					this.form.validateFields(['password2'], {
						force: true
					});
				}
			},
			// 本人保证选项验证	
			validateAgreement(rule, value, callback) {
				const form = this.form;
				if(!value) {
					callback('请确认信息无误!');
				} else {
					callback();
				}
			},
            // 获取个人中心相关数据
            async userRegists (values) {
                const res = await this.$store.dispatch('user/userRegists', values)
                if (res.code === '0000') {
                    this.$message.success('注册成功！');
                    this.form.resetFields();
                    // this.$router.go(0);
                    this.$router.push('/Login');
                }else{
                	this.$message.error(res.message);
                	this.getCodeUrl();
                }
            },
            // 获取短信验证码
            async SmsMsgSend (values) {

            	if (this.smsCodeText != '获取验证码') return;
            	let mobile = this.form.getFieldValue('mobile')
            	let imgCode = this.form.getFieldValue('imgCode')
            	if (!mobile) {
            		this.$message.error('手机号格式不正确')
            		return;
            	}
            	if (this.SmsMsgSendFlag) {
            		this.getCodeUrl();
            		return;
            	}
                const res = await this.$store.dispatch('SmsMsgSend', {
                	mobile: mobile,
                  	type: 'regist',
                	imgCode: imgCode
                })
                // console.log('res::',res)
                if (res.code === '0000') {
                    this.$message.success('短信验证码已发送！');
	            	if (this.smsCodeText == '获取验证码') {
	            		this.smsCodeText = 60;
	            		this.smsInterval = setInterval(()=>{
	            			this.smsCodeText = this.smsCodeText -1
	            			if (this.smsCodeText == 0) {
	            				this.smsCodeText = '获取验证码'
	            				clearInterval(this.smsInterval);
	            				this.smsInterval = ''
	            				this.SmsMsgSendFlag = true;
	            			}
	            		},1000)
	            	}
	            	
                    // this.form.resetFields();
                    // this.$router.go(0);
                }else{
                	this.$message.error(res.message);
                	this.getCodeUrl();
                }
            },
		}
	}
</script>

<style lang="scss">
	@import "./../../assets/css/register.scss";
</style>